package com.travelDevelop.commons.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


public class ForFile {
	
	
	
	
	
	@Transactional
	public String[] uploadDevelopFile(HttpServletRequest request,HttpServletResponse response,String ctxPath) throws IOException{
		response.setContentType("text/html;charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		// 设置接收的编码格式
		request.setCharacterEncoding("UTF-8");
		OutputStream bos = null;
		InputStream stream = null;
		StringBuffer newFile = null;
		String originalName =null;
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
			for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
				// 上传文件
				MultipartFile file = entity.getValue();
				//获取原始文件名称
				originalName = file.getOriginalFilename();
				//设置别名，以免存入服务器文件名冲突。
				newFile = new StringBuffer(originalName);
				newFile.insert(originalName.lastIndexOf("."), DateUtil.getCurDateStr("yyyyMMddHHmmSSS"));
				
				stream = file.getInputStream();
				File file1 = new File(ctxPath); // 添加了自动创建目录的功能
				if (!file1.exists()) // 如果文件目录不存在
					file1.mkdirs();
				bos = new FileOutputStream(ctxPath + "/" + newFile.toString());
				// 建立一个上传文件的输出流
				int bytesRead = 0;
				byte[] buffer = new byte[1024 * 100];
				while ((bytesRead = stream.read(buffer, 0, 1024 * 100)) != -1) {
					bos.write(buffer, 0, bytesRead);// 将文件写入服务器
				}
			}
			bos.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (stream != null) {
				stream.close();
			}
		}
		String[] arr={newFile.toString(), originalName};

		return arr;
	}

}
